<template>
  <web-view :src="url"></web-view>
</template>

<script setup>
import { ref , onMounted, onUnmounted } from 'vue'
import { onLoad ,onUnload } from '@dcloudio/uni-app'

const url = ref('')
let clearTimer = null

onLoad(() => {
	//从缓存中获取url
  url.value = uni.getStorageSync('PAY_URL') || '';
  console.log(url.value)
  
  // 保险措施：30分钟后自动清除
  clearTimer = setTimeout(() => {
    uni.removeStorageSync('PAY_URL');
  }, 60000*30);

  if (!url.value) {
    uni.showToast({ title: '该支付已过期，请重新发起支付', icon: 'none' });
    uni.navigateBack();
  }
  
  setupWebSocket()
});

//建立WebSocket连接并监听支付通知
let stompClient = null

const setupWebSocket = () => {
  // 使用uni-app的websocket连接
  const socketTask = uni.connectSocket({
    url: 'wss://4601f58c0c21.ngrok-free.app/websocket-pay-endpoint',
    complete: () => {}
  })
  let heartbeatInterval = null;
  socketTask.onOpen(() => {
    console.log('WebSocket连接成功')
    // 每30秒发送一次心跳
    heartbeatInterval = setInterval(() => {
        socketTask.send({
        data: JSON.stringify({type: 'heartbeat'}),
        success: () => console.log('心跳发送成功')
        })
    }, 30000)
  })
  
  socketTask.onMessage((res) => {
    const data = JSON.parse(res.data)
	console.log("后端信息：",res)
    if (data.trade_status === 'TRADE_SUCCESS') {
		uni.showToast({ title: '支付成功', icon: 'success' })
      // 支付成功后的处理，比如跳转回订单页
		console.log("支付成功。。。")
		//页面跳转
      // setTimeout(() => uni.redirectTo({url:'/pages/redirectPage/redirectPage'}), 1500)
	  
	  // 收到成功消息后延迟关闭
		setTimeout(() => {
			socketTask.close({
				success: () => console.log('支付完成，主动关闭连接'),
				fail: (err) => console.log('关闭连接失败', err)
			})
	    }, 5000) // 5秒后关闭
    }
  })
  
  socketTask.onError((err) => {
    console.error('WebSocket错误:', err)
  })
  
  socketTask.onClose(() => {
    console.log('WebSocket连接关闭')
  })
}

onUnmounted(() => {
  if (stompClient) {
    stompClient.disconnect()
  }
})

// 页面卸载时清理定时器
onUnload(() => {
  clearTimeout(clearTimer);
  
  //关闭WebSocket连接
    // if (socketTask) {
    //   socketTask.close({
    //     success: () => console.log('用户离开，已关闭连接'),
    //     fail: (err) => console.log('关闭连接失败', err)
    //   });
});
</script>